<!-- 文件名: app/templates/settings.html -->
{% extends "base.html" %}

{% block title %}系统设置 - 社交媒体监控{% endblock %}

{% block page_title %}系统设置{% endblock %}

{% block content %}
<div class="alert alert-info">
    <strong>提示：</strong> 修改这些设置会影响系统的行为。请谨慎操作！部分设置可能需要重启应用才能生效。
</div>

<div class="card mb-4">
    <div class="card-header">
        <h5>基本设置</h5>
    </div>
    <div class="card-body">
        <form id="basicSettingsForm">
            {% for setting in settings %}
                {% if ('delay' not in setting.key and
                      setting.key != 'retry_delays' and
                      setting.key != 'check_interval' and
                      setting.key != 'failed_download_retry_interval' and
                      'check_interval' not in setting.key and
                      'max_download_retries' not in setting.key and
                      'max_retries' not in setting.key and
                      'retry_task_enabled' not in setting.key and
                      'download_path' not in setting.key and
                      'hot_videos' not in setting.key and
                      'use_date_enabled' not in setting.key and
                      'download_video_orientation' not in setting.key and
                      'monitoring_enabled' not in setting.key) %}
                <div class="mb-3">
                    <label for="{{ setting.key }}" class="form-label">{{ setting.description }}</label>

                    {% if setting.key == "api_token" %}
                    <div class="input-group">
                        <input type="password" class="form-control" id="{{ setting.key }}" name="{{ setting.key }}" value="{{ setting.value }}" autocomplete="off">
                        <button class="btn btn-outline-secondary" type="button" onclick="togglePassword('{{ setting.key }}')">
                            <i class="bi bi-eye"></i>
                        </button>
                    </div>

                    {% elif setting.key == "max_retries" %}
                    <input type="number" class="form-control" id="{{ setting.key }}" name="{{ setting.key }}" value="{{ setting.value }}" min="1" max="10">
                    <small class="text-muted">推荐值：5，范围：1-10</small>

                    {% elif setting.key == "request_timeout" %}
                    <div class="input-group">
                        <input type="number" class="form-control" id="{{ setting.key }}" name="{{ setting.key }}" value="{{ setting.value }}" min="10">
                        <span class="input-group-text">秒</span>
                    </div>
                    <small class="text-muted">推荐值：120，最小值：10</small>

                    {% else %}
                    <input type="text" class="form-control" id="{{ setting.key }}" name="{{ setting.key }}" value="{{ setting.value }}">
                    {% endif %}

                    <div class="mt-1">
                        <small class="text-muted">最后更新: {{ setting.updated_at }}</small>
                    </div>
                </div>
                {% endif %}
            {% endfor %}
        </form>
    </div>
</div>

<div class="card mb-4">
    <div class="card-header">
        <h5>视频下载设置</h5>
    </div>
    <div class="card-body">
        <form id="videoDownloadSettingsForm">
            <div class="mb-3">
                <label class="form-label">视频方向筛选</label>
                <div class="d-flex align-items-center">
                    <div class="form-check form-check-inline">
                        <input class="form-check-input" type="radio" name="download_video_orientation" id="orientation_both" value="both"
                        {% if settings|selectattr('key', 'equalto', 'download_video_orientation')|map(attribute='value')|first|default('both') == 'both' %}checked{% endif %}>
                        <label class="form-check-label" for="orientation_both">全部下载</label>
                    </div>
                    <div class="form-check form-check-inline">
                        <input class="form-check-input" type="radio" name="download_video_orientation" id="orientation_portrait" value="portrait"
                        {% if settings|selectattr('key', 'equalto', 'download_video_orientation')|map(attribute='value')|first == 'portrait' %}checked{% endif %}>
                        <label class="form-check-label" for="orientation_portrait">仅竖屏视频</label>
                    </div>
                    <div class="form-check form-check-inline">
                        <input class="form-check-input" type="radio" name="download_video_orientation" id="orientation_landscape" value="landscape"
                        {% if settings|selectattr('key', 'equalto', 'download_video_orientation')|map(attribute='value')|first == 'landscape' %}checked{% endif %}>
                        <label class="form-check-label" for="orientation_landscape">仅横屏视频</label>
                    </div>
                </div>
                <div class="form-text">
                    <i class="bi bi-info-circle me-1"></i> 根据视频方向筛选下载内容。选择"全部下载"将同时下载横屏和竖屏视频。
                </div>
                <div class="alert alert-info mt-2">
                    <small>
                        <i class="bi bi-lightbulb me-1"></i> <strong>提示:</strong> 横屏视频宽高比大约为16:9，适合在电视、电脑上观看；竖屏视频宽高比约为9:16，适合在手机上观看。
                    </small>
                </div>
            </div>

            <!-- 新增：日期文件夹开关 -->
            <div class="mb-3 mt-4">
                <label class="form-label">日期文件夹设置</label>
                <div class="d-flex align-items-center">
                    <div class="form-check form-switch">
                        <input class="form-check-input" type="checkbox" role="switch" id="use_date_enabled" name="use_date_enabled"
                               {% if settings|selectattr('key', 'equalto', 'use_date_enabled')|map(attribute='value')|first|default('false') == 'true' %}checked{% endif %}>
                        <label class="form-check-label" for="use_date_enabled">启用日期文件夹</label>
                    </div>
                </div>
                <div class="form-text">
                    <i class="bi bi-info-circle me-1"></i> 启用后，下载的视频将按日期保存在对应的文件夹中（例如：2025-05-14/）。
                </div>
                <div class="alert alert-info mt-2">
                    <small>
                        <i class="bi bi-lightbulb me-1"></i> <strong>提示:</strong> 使用日期文件夹可以更方便地按时间查找和管理视频，但会增加文件夹层级。
                    </small>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- 平台特定延迟设置卡片 -->
<div class="card mb-4">
    <div class="card-header">
        <h5>平台延迟设置</h5>
    </div>
    <div class="card-body">
        <form id="delaySettingsForm">
            <div class="row">
                <!-- TikTok部分 -->
                <div class="col-md-4 mb-4">
                    <div class="card">
                        <div class="card-header platform-tiktok text-white">
                            TikTok 延迟设置
                        </div>
                        <div class="card-body">
                            {% for setting in settings %}
                                {% if setting.key == "tiktok_user_delay" or setting.key == "tiktok_video_delay" %}
                                <div class="mb-3">
                                    <label for="{{ setting.key }}" class="form-label">{{ setting.description }}</label>
                                    <div class="input-group">
                                        <input type="number" class="form-control" id="{{ setting.key }}" name="{{ setting.key }}" value="{{ setting.value }}" min="0" step="0.5">
                                        <span class="input-group-text">秒</span>
                                    </div>
                                </div>
                                {% endif %}
                            {% endfor %}
                        </div>
                    </div>
                </div>

                <!-- 抖音部分 -->
                <div class="col-md-4 mb-4">
                    <div class="card">
                        <div class="card-header platform-douyin text-white">
                            抖音延迟设置
                        </div>
                        <div class="card-body">
                            {% for setting in settings %}
                                {% if setting.key == "douyin_user_delay" or setting.key == "douyin_video_delay" %}
                                <div class="mb-3">
                                    <label for="{{ setting.key }}" class="form-label">{{ setting.description }}</label>
                                    <div class="input-group">
                                        <input type="number" class="form-control" id="{{ setting.key }}" name="{{ setting.key }}" value="{{ setting.value }}" min="0" step="0.5">
                                        <span class="input-group-text">秒</span>
                                    </div>
                                </div>
                                {% endif %}
                            {% endfor %}
                        </div>
                    </div>
                </div>

                <!-- Instagram部分 -->
                <div class="col-md-4 mb-4">
                    <div class="card">
                        <div class="card-header platform-instagram text-dark">
                            Instagram 延迟设置
                        </div>
                        <div class="card-body">
                            {% for setting in settings %}
                                {% if setting.key == "instagram_user_delay" or setting.key == "instagram_video_delay" %}
                                <div class="mb-3">
                                    <label for="{{ setting.key }}" class="form-label">{{ setting.description }}</label>
                                    <div class="input-group">
                                        <input type="number" class="form-control" id="{{ setting.key }}" name="{{ setting.key }}" value="{{ setting.value }}" min="0" step="0.5">
                                        <span class="input-group-text">秒</span>
                                    </div>
                                </div>
                                {% endif %}
                            {% endfor %}
                        </div>
                    </div>
                </div>

                <!-- 快手部分 -->
                <div class="col-md-4 mb-4">
                    <div class="card">
                        <div class="card-header platform-kuaishou text-white">
                            快手 延迟设置
                        </div>
                        <div class="card-body">
                            {% for setting in settings %}
                                {% if setting.key == "kuaishou_user_delay" or setting.key == "kuaishou_video_delay" %}
                                <div class="mb-3">
                                    <label for="{{ setting.key }}" class="form-label">{{ setting.description }}</label>
                                    <div class="input-group">
                                        <input type="number" class="form-control" id="{{ setting.key }}" name="{{ setting.key }}" value="{{ setting.value }}" min="0" step="0.5">
                                        <span class="input-group-text">秒</span>
                                    </div>
                                </div>
                                {% endif %}
                            {% endfor %}
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>

<div class="card mb-4">
    <div class="card-header">
        <h5>平台监控设置</h5>
    </div>
    <div class="card-body">
        <form id="monitoringSettingsForm">
            <div class="row">
                <!-- TikTok部分 -->
                <div class="col-md-4 mb-4">
                    <div class="card h-100">
                        <div class="card-header platform-tiktok text-white d-flex justify-content-between align-items-center">
                            <span>TikTok 监控设置</span>
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" role="switch" id="tiktok_monitoring_enabled" name="tiktok_monitoring_enabled"
                                       {% if settings|selectattr('key', 'equalto', 'tiktok_monitoring_enabled')|map(attribute='value')|first|default('true') == 'true' %}checked{% endif %}>
                                <label class="form-check-label text-white" for="tiktok_monitoring_enabled">启用</label>
                            </div>
                        </div>
                        <div class="card-body">
                            <div class="mb-3">
                                <label for="tiktok_check_interval" class="form-label">检查间隔</label>
                                <div class="input-group">
                                    <input type="number" class="form-control" id="tiktok_check_interval" name="tiktok_check_interval"
                                           value="{{ settings|selectattr('key', 'equalto', 'tiktok_check_interval')|map(attribute='value')|first|default('21600') }}" min="60">
                                    <span class="input-group-text">秒</span>
                                </div>
                                <small class="text-muted">推荐：21600（6小时）</small>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 抖音部分 -->
                <div class="col-md-4 mb-4">
                    <div class="card h-100">
                        <div class="card-header platform-douyin text-white d-flex justify-content-between align-items-center">
                            <span>抖音监控设置</span>
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" role="switch" id="douyin_monitoring_enabled" name="douyin_monitoring_enabled"
                                       {% if settings|selectattr('key', 'equalto', 'douyin_monitoring_enabled')|map(attribute='value')|first|default('true') == 'true' %}checked{% endif %}>
                                <label class="form-check-label text-white" for="douyin_monitoring_enabled">启用</label>
                            </div>
                        </div>
                        <div class="card-body">
                            <div class="mb-3">
                                <label for="douyin_check_interval" class="form-label">检查间隔</label>
                                <div class="input-group">
                                    <input type="number" class="form-control" id="douyin_check_interval" name="douyin_check_interval"
                                           value="{{ settings|selectattr('key', 'equalto', 'douyin_check_interval')|map(attribute='value')|first|default('28800') }}" min="60">
                                    <span class="input-group-text">秒</span>
                                </div>
                                <small class="text-muted">推荐：28800（8小时）</small>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Instagram部分 -->
                <div class="col-md-4 mb-4">
                    <div class="card h-100">
                        <div class="card-header platform-instagram text-dark d-flex justify-content-between align-items-center">
                            <span>Instagram监控设置</span>
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" role="switch" id="instagram_monitoring_enabled" name="instagram_monitoring_enabled"
                                       {% if settings|selectattr('key', 'equalto', 'instagram_monitoring_enabled')|map(attribute='value')|first|default('true') == 'true' %}checked{% endif %}>
                                <label class="form-check-label text-dark" for="instagram_monitoring_enabled">启用</label>
                            </div>
                        </div>
                        <div class="card-body">
                            <div class="mb-3">
                                <label for="instagram_check_interval" class="form-label">检查间隔</label>
                                <div class="input-group">
                                    <input type="number" class="form-control" id="instagram_check_interval" name="instagram_check_interval"
                                           value="{{ settings|selectattr('key', 'equalto', 'instagram_check_interval')|map(attribute='value')|first|default('25200') }}" min="60">
                                    <span class="input-group-text">秒</span>
                                </div>
                                <small class="text-muted">推荐：25200（7小时）</small>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 快手部分 -->
                <div class="col-md-4 mb-4">
                    <div class="card h-100">
                        <div class="card-header platform-kuaishou text-white d-flex justify-content-between align-items-center">
                            <span>快手 监控设置</span>
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" role="switch" id="kuaishou_monitoring_enabled" name="kuaishou_monitoring_enabled"
                                       {% if settings|selectattr('key', 'equalto', 'kuaishou_monitoring_enabled')|map(attribute='value')|first|default('true') == 'true' %}checked{% endif %}>
                                <label class="form-check-label text-white" for="kuaishou_monitoring_enabled">启用</label>
                            </div>
                        </div>
                        <div class="card-body">
                            <div class="mb-3">
                                <label for="kuaishou_check_interval" class="form-label">检查间隔</label>
                                <div class="input-group">
                                    <input type="number" class="form-control" id="kuaishou_check_interval" name="kuaishou_check_interval"
                                           value="{{ settings|selectattr('key', 'equalto', 'kuaishou_check_interval')|map(attribute='value')|first|default('18000') }}" min="60">
                                    <span class="input-group-text">秒</span>
                                </div>
                                <small class="text-muted">推荐：18000（5小时）</small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>

<div class="card mb-4">
    <div class="card-header">
        <h5>下载重试任务设置</h5>
    </div>
    <div class="card-body">
        <form id="retrySettingsForm">
            <div class="card">
                <div class="card-header bg-warning text-dark d-flex justify-content-between align-items-center">
                    <span>视频下载重试设置</span>
                    <div class="form-check form-switch">
                        <input class="form-check-input" type="checkbox" role="switch" id="retry_task_enabled" name="retry_task_enabled"
                               {% if settings|selectattr('key', 'equalto', 'retry_task_enabled')|map(attribute='value')|first|default('true') == 'true' %}checked{% endif %}>
                        <label class="form-check-label text-dark" for="retry_task_enabled">启用</label>
                    </div>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <label for="failed_download_retry_interval" class="form-label">重试检查间隔</label>
                        <div class="input-group">
                            <input type="number" class="form-control" id="failed_download_retry_interval" name="failed_download_retry_interval"
                                   value="{{ settings|selectattr('key', 'equalto', 'failed_download_retry_interval')|map(attribute='value')|first|default('14400') }}" min="3600">
                            <span class="input-group-text">秒</span>
                        </div>
                        <small class="text-muted">推荐：14400（4小时）- 系统将每隔此时间检查并重试下载失败的视频</small>
                    </div>

                    <div class="mb-3">
                        <label for="max_download_retries" class="form-label">最大重试次数</label>
                        <div class="input-group">
                            <input type="number" class="form-control" id="max_download_retries" name="max_download_retries"
                                   value="{{ settings|selectattr('key', 'equalto', 'max_download_retries')|map(attribute='value')|first|default('2') }}" min="1" max="10">
                            <span class="input-group-text">次</span>
                        </div>
                        <small class="text-muted">每个下载失败的视频最多重试的次数</small>
                    </div>

                    <div class="alert alert-info">
                        <i class="bi bi-info-circle me-2"></i>下载重试任务会定期检查下载失败的视频，并尝试重新下载。视频达到最大重试次数后将不再重试。
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>

<div class="card mb-4">
    <div class="card-header">
        <h5>热门视频设置</h5>
    </div>
    <div class="card-body">
        <form id="hotVideosSettingsForm">
            <div class="card">
                <div class="card-header bg-danger text-white d-flex justify-content-between align-items-center">
                    <span>抖音热门视频设置</span>
                    <div class="form-check form-switch">
                        <input class="form-check-input" type="checkbox" role="switch" id="hot_videos_enabled" name="hot_videos_enabled"
                               {% if settings|selectattr('key', 'equalto', 'hot_videos_enabled')|map(attribute='value')|first|default('true') == 'true' %}checked{% endif %}>
                        <label class="form-check-label text-white" for="hot_videos_enabled">启用</label>
                    </div>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <label for="hot_videos_check_interval" class="form-label">检查间隔</label>
                        <div class="input-group">
                            <input type="number" class="form-control" id="hot_videos_check_interval" name="hot_videos_check_interval"
                                   value="{{ settings|selectattr('key', 'equalto', 'hot_videos_check_interval')|map(attribute='value')|first|default('86400') }}" min="3600">
                            <span class="input-group-text">秒</span>
                        </div>
                        <small class="text-muted">推荐：86400（1天）</small>
                    </div>

                    <div class="mb-3">
                        <label for="hot_videos_daily_hour" class="form-label">每天拉取时间（小时）</label>
                        <div class="input-group">
                            <input type="number" class="form-control" id="hot_videos_daily_hour" name="hot_videos_daily_hour"
                                   value="{{ settings|selectattr('key', 'equalto', 'hot_videos_daily_hour')|map(attribute='value')|first|default('6') }}" min="0" max="23">
                            <span class="input-group-text">时</span>
                        </div>
                        <small class="text-muted">每天在此时刻自动拉取热门视频（0-23小时）</small>
                    </div>

                    <div class="mb-3">
                        <label for="hot_videos_pages" class="form-label">拉取页数</label>
                        <div class="input-group">
                            <input type="number" class="form-control" id="hot_videos_pages" name="hot_videos_pages"
                                   value="{{ settings|selectattr('key', 'equalto', 'hot_videos_pages')|map(attribute='value')|first|default('3') }}" min="3" max="10">
                            <span class="input-group-text">页</span>
                        </div>
                        <small class="text-muted">每次自动拉取的页数（每页约20个视频）</small>
                    </div>

                    <!-- 新增的数据清理设置 -->
                    <div class="mb-3">
                        <label for="hot_videos_retention_days" class="form-label">保留天数</label>
                        <div class="input-group">
                            <input type="number" class="form-control" id="hot_videos_retention_days" name="hot_videos_retention_days"
                                   value="{{ settings|selectattr('key', 'equalto', 'hot_videos_retention_days')|map(attribute='value')|first|default('7') }}" min="1" max="90">
                            <span class="input-group-text">天</span>
                        </div>
                        <small class="text-muted">超过此天数的且未下载的视频将被自动删除</small>
                    </div>

                    <div class="mb-3">
                        <label for="hot_videos_max_count" class="form-label">最大保留数量</label>
                        <div class="input-group">
                            <input type="number" class="form-control" id="hot_videos_max_count" name="hot_videos_max_count"
                                   value="{{ settings|selectattr('key', 'equalto', 'hot_videos_max_count')|map(attribute='value')|first|default('1000') }}" min="100" max="10000">
                            <span class="input-group-text">个</span>
                        </div>
                        <small class="text-muted">超过此数量时自动删除最旧的且未下载的视频</small>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- 提交按钮 -->
<div class="d-flex justify-content-center mb-5">
    <button type="button" class="btn btn-primary btn-lg" onclick="saveAllSettings()">保存所有设置</button>
    <button type="button" class="btn btn-secondary btn-lg ms-3" onclick="location.reload()">重置</button>
</div>
{% endblock %}

{% block scripts %}
<script>
function togglePassword(id) {
    const input = document.getElementById(id);
    if (input.type === 'password') {
        input.type = 'text';
    } else {
        input.type = 'password';
    }
}

async function saveAllSettings() {
    // 收集所有表单中的设置
    const allSettings = new FormData(document.getElementById('basicSettingsForm'));
    const delaySettings = new FormData(document.getElementById('delaySettingsForm'));
    const monitoringSettings = new FormData(document.getElementById('monitoringSettingsForm'));
    const hotVideosSettings = new FormData(document.getElementById('hotVideosSettingsForm'));
    const retrySettings = new FormData(document.getElementById('retrySettingsForm'));
    const videoDownloadSettings = new FormData(document.getElementById('videoDownloadSettingsForm'));

    // 合并设置
    for (const [key, value] of delaySettings.entries()) {
        allSettings.append(key, value);
    }

    for (const [key, value] of hotVideosSettings.entries()) { // 新增
        allSettings.append(key, value);
    }

    // 合并重试任务设置
    for (const [key, value] of retrySettings.entries()) {
        allSettings.append(key, value);
    }

    // 合并视频下载设置
    for (const [key, value] of videoDownloadSettings.entries()) {
        allSettings.append(key, value);
    }

    // 处理checkbox值
    const checkboxes = [
        'tiktok_monitoring_enabled',
        'douyin_monitoring_enabled',
        'instagram_monitoring_enabled',
        'hot_videos_enabled',
        'kuaishou_monitoring_enabled',
        'retry_task_enabled',
        'use_date_enabled'
    ];
    for (const key of checkboxes) {
        const checkbox = document.getElementById(key);
        // 如果checkbox存在但在FormData中不存在（未选中状态），手动添加为false
        if (checkbox && !monitoringSettings.has(key)  && !hotVideosSettings.has(key) && !retrySettings.has(key)) {
            allSettings.append(key, 'false');
        }
    }

    for (const [key, value] of monitoringSettings.entries()) {
        // 处理复选框的值，将"on"转换为"true"
        if (checkboxes.includes(key) && value === 'on') {
            allSettings.append(key, 'true');
        } else {
            allSettings.append(key, value);
        }
    }

    for (const [key, value] of hotVideosSettings.entries()) {
        if (checkboxes.includes(key) && value === 'on') {
            allSettings.append(key, 'true');
        } else {
            allSettings.append(key, value);
        }
    }

    for (const [key, value] of retrySettings.entries()) {
        if (checkboxes.includes(key) && value === 'on') {
            allSettings.append(key, 'true');
        } else {
            allSettings.append(key, value);
        }
    }

     // 处理视频下载设置中的复选框
    for (const [key, value] of videoDownloadSettings.entries()) {
        if (checkboxes.includes(key) && value === 'on') {
            allSettings.append(key, 'true');
        } else {
            allSettings.append(key, value);
        }
    }

    let hasError = false;

    for (const [key, value] of allSettings.entries()) {
        try {
            const response = await fetch(`/api/settings/${key}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ value: value }),
            });

            if (!response.ok) {
                const errorData = await response.json();
                alert(`保存设置 "${key}" 失败: ${errorData.detail}`);
                hasError = true;
            }
        } catch (error) {
            alert(`保存设置 "${key}" 时发生错误: ${error.message}`);
            hasError = true;
        }
    }

    if (!hasError) {
        alert('所有设置已保存');
        location.reload();
    }
}
</script>
{% endblock %}